<!DOCTYPE html>
<%@ page language="java" import="com.compuvest.web.*,java.util.ArrayList,java.util.Map,java.text.DecimalFormat" pageEncoding="UTF-8" %>

<%@ taglib uri="/WEB-INF/tld/head.tld" prefix="head" %>

<jsp:useBean id="sb" class="SQLBean" scope="application"/>
<jsp:useBean id="advertShow" class="AdvertShow" scope="application"/>
<jsp:useBean id="basket" class="Basket" scope="session"/>
<%!
    Items basketItems = new Items(); // for getResellerPriceLine()
%>
<%
    String https = application.getInitParameter("https");
    String http = application.getInitParameter("http");

    DecimalFormat priceForm = new DecimalFormat("$#,##0.00");

    String countryCode = advertShow.getString(request.getParameter("CountryCode"), "US");
    String zipCode = advertShow.getString(request.getParameter("ZipCode"), "");

    basket.setShippingCost(0d);

    String invalidPromo = "";
    String promoCode = request.getParameter("promo");
    // delete items
    String[] deleteIDs = request.getParameterValues("delete");
    // update quantity
    String[] quantity = request.getParameterValues("quantity");
    // add item
    String iidd = request.getParameter("iidd");
    if(deleteIDs != null) { // delete items
	for(String itemID : deleteIDs) {

	    basket.setQuantity(advertShow.getInt(itemID, 0), 0, null);
	}
    }
    else if(quantity != null) { // update quantity
        // update or activate promo code
        if(promoCode != null && promoCode.length() > 8) { // CVR0001- CVR000001
            String custPromoCode = promoCode.trim().toUpperCase().substring(2); // CVR0001 -> R0001
            char whatPromoCode = custPromoCode.charAt(0);  // A or R
            if(whatPromoCode == 'R') {
		if(!basket.checkPromotionCode(custPromoCode)) {
                    if(basket.getPromotion() == null) {
			invalidPromo = "&nbsp;&nbsp;&nbsp;<font size='-1' color='red'>We're sorry, but this promotion code is invalid for this item.</font>";
                    }
                    else {
			invalidPromo = "&nbsp;&nbsp;&nbsp;<font size='-1' color='red'>We're sorry, but you can use only one promotional code at the time.</font>";
                    }
		}
            }
            // N - nextag, P - pricegraber, M - facebook
//          else if(whatPromoCode == 'P' || whatPromoCode == 'N') {
            else {
		PromotionCode code = sb.getPromoCodeForBasket(custPromoCode);
		if(code == null) {
                    invalidPromo = "&nbsp;&nbsp;&nbsp;<font size='-1' color='red'>We're sorry, but this coupon code is invalid.</font>";
		}
//		else if(code.getPromoID() != 0 && code.getCount() > 0) {
//                  invalidPromo = "&nbsp;&nbsp;&nbsp;<font size='-1' color='red'>You coupon is in use , right now.</font>";
//		}
		else {
                    basket.setPromotion(code);
		}
            }
        }

        String[] quantityID = request.getParameterValues("qtyID");
        String[] warranties = request.getParameterValues("warranty");
        for(int i = 0; i < quantity.length; i++) {

            int qty = advertShow.getInt(quantity[i], 0);
            int qtyID = advertShow.getInt(quantityID[i], 0);

            basket.setQuantity(qtyID, qty, warranties[i]);
        }
    }
    else if(iidd != null) { // add item
        int itemID = advertShow.getInt(iidd, 0);

        if(itemID != 0) {
            basket.addItem(new ItemsInBasket(sb.getItemForBasket(itemID), basket.getReseller()));
        }
    }
%>
<html>
<head>
<title><%= application.getInitParameter("CompanyName") %></title>
<%@include file="./incl/scripts.txt" %>
<script type='text/javascript' src='https://static-na.payments-amazon.com/cba/js/us/PaymentWidgets.js'></script>
</head>
<body>

<div id='cvbody'>

 <head:show />

 <div id='cvcont'>
  <table id='cvmain'>
  <colgroup><col width='200px'/><col width='*'/><col width='160px'/></colgroup>
  <tbody>
   <tr>
    <td id='cvleft' valign="top">


    </td>
    <td id='cvcenter' align="center" valign="top">

<%
    // select advert coupon
    String advertImage = basket.getCouponShow(advertShow);
    out.write(advertImage);
%>

   <%-- shopping cart --%>
<%
    if(basket.notEmpty()) {
%>
   <br/>
   <form id='Basket' action='<%= http %>Basket.jsp' method='POST'>
   <div class='htlt'>Shopping Cart</div>
   <table style='background-color:white;border:1px solid #d4d4d4;width:90%;font-size:12px;font-weight:bold;' border="1">
   <colgroup><col width='12%'/><col width='54%'/><col width='10%'/><col width='6%'/><col width='6%'/><col width='10%'/><col width='2%'/></colgroup>
    <tr class='bsm' height='26'>
     <th>Part #</th><th>Product Name</th><th>Price</th><th>Stock</th><th>Qty</th><th>Amount</th><th>X</th>
    </tr>
<%
	boolean ground = false;
	String rowspan = "";
	for(ItemsInBasket item : basket.getContents()) {
	    rowspan = (item.getWarrantyMask() & item.EXTENDED_WARRANTY) != 0 ? "rowspan='2'" : "";
%>
    <tr style='background-color:#ffff<%= (ground = !ground) ? "df" : "ff" %>;text-align:center;'>
     <td <%= rowspan %> id='nowrap'><%= item.getAccwareCode() %><div style='font-size:10px;color:blue;'><%= item.getCondition() %></div></td>
     <td style="text-align:left;padding:1px 5px;">
     <a href="<%= http %>Desc.jsp?iid=<%= item.getItemID() %>" class='tlink'><%= item.getItemName() %></a>
      <%= basket.getReseller() ? "<br/>" + basketItems.getResellerPriceLine(item) : "" %>
      <%= item.getPromotionPriceString(false) %>
     </td>
     <td>
<%	if(basket.getReseller() && item.getResPrice1() != 0d) { %>
      <div class='prices'><%= priceForm.format(item.getPrice()) %></div>
<%	} %>
     <%= priceForm.format(item.getSellPrice()) %><br/>
    <input type='hidden' name='qtyID' value='<%= item.getItemID() %>'/>
     </td>
     <td <%= rowspan %>><%= item.getStock() ? "Yes" : Integer.toString(item.getQuantity()) %></td>
     <td <%= rowspan %>><input type='text' name='quantity' size='2' maxlength='3' value='<%= item.getTotalQuantity() %>' onChange="this.value=isInt(this.value);"/></td>
     <td><%= priceForm.format(item.getSellPrice() * item.getTotalQuantity()) %></td>
     <td <%= rowspan %>><input type='checkbox' name='delete' value='<%= item.getItemID() %>' onClick="document.id('Basket').submit();"/></td>
    </tr>
<%
	    // warranty &&  extended warranty any bit up ?
	    if((item.getWarrantyMask() & item.EXTENDED_WARRANTY) != 0) {
%>
    <tr style='background-color:#ffff<%= ground ? "df" : "ff" %>;text-align:center;'>
     <td style="text-align:left;padding:1px 5px;">
      <div style='font-size:10px;'>Warranty : <%= item.getWarrantyDays() %>.</div>

      <span id='wty' class='tipz'>Extended warranty : <img id='wty' class='tipz' src='../img/it/hlp.gif' alt='Extended warranty'/></span>

       <select name='warranty' size='1' style='width:150px;font-size:8pt;' onChange="document.id('Basket').submit();">
        <option value='0|0.00'>No Thanks</option>
        <%=  item.getExtendedWarrantyOptions(item.getWarrantyPrice(), true) %>
     </select>
     </td>
     <td><%= item.getWarrantyPrice() == 0d ? "" : priceForm.format(item.getWarrantyPrice()) %></td>
     <td><%= item.getWarrantyPrice() == 0d ? "" : priceForm.format(item.getWarrantyTotal()) %></td>
    </tr>
<%
	    }
	    else {
                out.write("<input type='hidden' name='warranty' value='0'/>");
	    }
	}
%>
    <tr height='28'>
     <td colspan='7' style='padding-right:35px;text-align:right;vertical-align:middle;'>
      <font color='red'><%= basket.getCouponMessage(true) %></font><br/>
       Total Amount : <%= priceForm.format(basket.getTotal(true)) %>
      </td>
    </tr>
    <tr height='28'>
     <td colspan='7' style='text-align:left;padding-left:9px;'> Promotion Code : <input id='promo' type='text' name='promo' size='10' maxlength='10' value=''/>
      <input onClick='validPromo();' type='button' value='Activate' name='Activate'/><%= invalidPromo %>
<%
	if(basket.getCoupon() != null && invalidPromo.length() == 0) {
%>
 <font color='red'>&nbsp; You will receive the coupon code for $<%= basket.getCoupon().getPrice() %> off in the confirmation email once your order is completed.</font>
<%
	}
%>
     </td>
    </tr>
   </table>

   <table style='background:url(../img/it/tbg.png) repeat-x scroll 0 0 transparent;width:90%;'>
    <tr>
    <td><a class='btlgr' href='<%= session.getAttribute("backItemsPage") == null ? http : (String)session.getAttribute("backItemsPage") %>'>Continue Shopping</a></td>
    <td width='80%'>&nbsp;</td>
    <td style='padding-right:4px;'>
     <div id="AmazonInlineWidget"><img src="https://payments.amazon.com/gp/cba/button?cartOwnerId=A3S3XOO7JN6CF5&size=large&color=orange&background=white&type=inlineCheckout" style="cursor:pointer;" alt="Amazon Checkout"/></div>
    </td>
    <td><a class='btgr hbl2' href='javascript:;' onClick="javascript:window.open('<%= application.getInitParameter("info") %>PopPolicies.jsp','','toolbar=no,scrollbars=yes,width=650,height=650,left=50,top=50');">Return<br/>Policy</a></td>
    <td><a class='btyw hbl1' href='javascript:;' onClick="document.id('Basket').submit();">Update</a></td>
    <td><a id="checkout" class='btgr hbl1' href='<%= https %>CustomerForm.jsp'>Check Out</a></td>
    </tr>
   </table>
<script type='text/javascript'>
new CBA.Widgets.InlineCheckoutWidget({
    merchantId: 'A3S3XOO7JN6CF5',
    onAuthorize: function(widget) {
        window.location = '<%= https %>AmazonShipping.jsp?id=' + widget.getPurchaseContractId();
    }
}).render("AmazonInlineWidget");
</script>

<br/><br/>

   <div class='htlt'>Shipping Calculator</div>
   <table class='part' style='border:1px solid #d4d4d4;width:80%;background-color:#ffffdf;'>
    <tr class='bsm' height='26'><td colspan='4'>&nbsp;</td></tr>
    <tr>
     <td colspan='2' align='center'>Country :
     <select class='cntry' onChange="document.id('Basket').submit();" name="CountryCode">
     <%= advertShow.getCountryList(countryCode) %>
     </select>
     </td>
     <td colspan='2' id='nowrap'>&nbsp;Enter your ZIP : <input class='zip' type='text' value='<%= zipCode %>' maxLength='10' size='15' name="ZipCode"/></td>
    </tr>
    <tr class='bsm' height='26' align='right'>
     <td colspan='4'><a class='btgr hbl1' href='javascript:;' onClick="document.id('Basket').submit();">Update</a></td>
    </tr>
    <tr>
<%
	// not show if zipCode=empty
	if(!"".equals(zipCode) || !"US".equals(countryCode)) {

	    ArrayList<ShipRate> shippRate;
	    if("US".equals(countryCode)) {
                shippRate = sb.getShippingChartUS(zipCode, basket.getTotalWeight());
            }
	    else {
                shippRate = sb.getShippingChart(countryCode, basket.getTotalWeight());
            }

	    StringBuilder jsc = new StringBuilder();
	    StringBuilder rdo = new StringBuilder();
	    rdo.append("<td align='right'>Shipping method :&nbsp;&nbsp;</td>");
	    rdo.append("<td style='border-left:1px solid #d4d4d4;text-align:left;padding-left:5px;'>");
	    jsc.append("<script type='text/javascript'>function upship(ship){");

	    for(ShipRate ship : shippRate) {
                String groundLine = priceForm.format(ship.getShipPrice()) + " - " + ship.getDescription();
                // if froogle and all googleXX and cws than free shipping (fdg == ground)
                if("fdg".equals(ship.getShipCode())) {
                    String advName = basket.getCompuvestCookies().getAdvertSite();
                    if(advertShow.isFreeShipping(advName)) {
                    //if(advName.contains("oogle") ||
                    //    advertShow.getAdvertID(advName) == AdvertShow.ADV_CWS ||
                    //    advertShow.getAdvertID(advName) == AdvertShow.ADV_CWM ||
                    //    advertShow.getAdvertID(advName) == AdvertShow.BING) {

                        ship.setShipPrice(0d, 0d);
                        groundLine = ShipRate.STR_FREE_SHIPPING;
                    }
                }
		rdo.append("<input type='radio' name='ship_opt' value='").append(ship.getShipCode());
		rdo.append("' onClick='upship(this.value);'/> ");
		rdo.append( groundLine ).append("<br/>");

		jsc.append("if(ship=='").append(ship.getShipCode()).append("'){");
		jsc.append("document.id('spcst').set('text','$' + numberFormat(").append(ship.getShipPrice()).append("));");
		jsc.append("document.id('grntot').set('text','$' + numberFormat(").append(ship.getShipPrice() + basket.getTotal(true)).append("));");
		jsc.append("}");
	    }
	    rdo.append("</td>");
	    jsc.append("}</script>\n");

	    if(shippRate != null) {
                out.write(rdo.toString());
                out.write(jsc.toString());
%>
     <td style='border-left:1px solid #d4d4d4;text-align:right;'>
      Shipping cost :<br/>
      Grand total :
     </td>
     <td width='100'>
      <div style='padding-left:5px;text-align:left;color:red;'>
       <span id="spcst">$0.00</span><br/>
       <span id="grntot">$0.00</span>
      </div>
     </td>
    </tr>
    <tr><td colspan='2' style="text-align:center;color:red;padding:5px 10px;font-size:10px;">Alaska, Hawaii and Guam  may have additional surcharges.  For accurate shipping costs please email <a href="mailto:info@compuvest.com">info@compuvest.com</a></td><td colspan='2' style="border-left:1px solid #d4d4d4;"></td></tr>
    <tr class='bsm' height='26'><td colspan='4'>&nbsp;</td></tr>
<%
	    }
	}
%>
   </table>
   </form>
<%
    } //(basket.notEmpty())
    else {
%>
<br/>
<span class='htlt'>There are currently no items in your shopping cart.</span>
<br/><br/>
<a class='btlgr' href='<%= session.getAttribute("backItemsPage") == null ? http : (String)session.getAttribute("backItemsPage") %>'>Continue Shopping</a>
<%
    }
%>

    </td>
    <td id='cvright' valign="top">&nbsp;</td>
   </tr>
  </tbody>
  </table>
 </div>

 <div id='cvfoot'></div>
</div>

</body>
</html>
